package com.haust.config.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Auther: csp1999
 * @Date: 2020/08/12/17:24
 * @Description: 自定义日志处理组件
 */
@Aspect// aop 日志处理
@Component// 交给Spring容器管理
public class LogAspect {

    // 获取日志记录器
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 切入点
    @Pointcut("execution(* com.haust.controller.*.*(..))")// 拦截controller包下任何类下的任何方法下的所有参数
    public void log() {// 切面
    }

    // 前置通知,在切面之前执行
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();// 获取request

        // 获取请求对象的url/ip
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();

        // 获取执行方法全类名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();// 获取请求参数

        // 实例化RequestLog
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);

        logger.info("----------doBefore----------");
        logger.info("请求内容 : {}", requestLog);
        // 结果：请求内容 : RequestLog{url='http://localhost/blog/test/test04/1/%E5%B0%8F%E6%98%8E', ip='0:0:0:0:0:0:0:1', classMethod='com.haust.web.TestController.test04', args=[1, 小明]}
    }

    // 后置通知,在切面之后执行
    @After("log()")
    public void doAfter() {
        logger.info("----------doAfter----------");
    }

    // 切入点拦截的方法执行结束后，捕获返回内容
    @AfterReturning(returning = "result", pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("捕获返回内容 : {}", result);// 结果：捕获返回内容 : id=1,name=小明
    }

    /*
     *  记录日志内容:
     *      请求 url
     *      访问者 ip
     *      调用方法 classMethod
     *      参数 args
     *      返回内容
     */
    private class RequestLog {

        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "RequestLog{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}

